// pages/home/home.js
import api from "../../config/api";
import { shareOptions } from "../../utils/access";
import request from "../../utils/request";
import { stringify, getStorage, jump, fixed } from "../../utils/utils";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 帖子列表
    list: [],
    // 圈子列表
    circleList: [],
    page: 1,
    total: 0,
    isDone: false,
    // 用户id
    id: null,
    // 详情数据
    info: {},
    // 用户勋章列表
    medalList: [],
    // 用户勋章个数
    medalCount: [],
    detailInfo:'',
    infoComplete: '',
    //  标签页选中项
    tabIndex: '1',
    // 类型初始滑动位置
    typeScrollX: 0,
  },
  // 点赞loading
  loading: false,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userId = getStorage('userId')
    this.setData({
      id: options?.id,
      userId
    })
    this.getList(1)
  },
  jumpInfo: function(){
    const { id, userId, infoComplete } = this.data
    if (id == userId) {
      if (infoComplete === 1) return
      const isComplete = stringify(infoComplete)
      wx.navigateTo({
        url: `/pages/residenceCertification/residenceCertification?isComplete=${isComplete}`,
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.followModal = this.selectComponent('#followModal')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.isShareing) {
      this.isShareing = false
      return
    }
    this.getInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getInfo()
    this.setData({
      page: 1,
      isDone: false,
    })
    this.getList(1)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let { page, total } = this.data
    if (page < total) {
      page++
      this.setData({
        page
      })
      this.getList(page)
    } else {
      this.setData({
        isDone: true
      })
    }
  },

  /**
   * 获取列表
   * @param {*} page 当前页
   */
  async getList(page) {
    const { id, tabIndex } = this.data
    const res = await request.get(
      tabIndex === '1' ? api.homeList : api.homeCircleList,
      {
        page,
        size: 10,
        userId: id,
      }
    )
    const data = (res?.data?.records || []).map(item => {
      item.picUrls = (item?.picUrls || []).filter(Boolean)
      let picUrls = item.picUrls.slice(0, 3)
      return {
        ...item,
        picUrls,
        picMore: item?.picUrls?.length - picUrls.length
      }
    })
    const listData = page === 1 ? data : [
      ...this.data[tabIndex === '1' ? 'list' : 'circleList'],
      ...data,
    ]
    this.setData({
      [tabIndex === '1' ? 'list' : 'circleList']: listData,
      total: res?.data?.pages,
      isDone: res?.data?.total === listData.length
    })
    wx.stopPullDownRefresh()
  },
  // 获取详情数据
  async getInfo() {
    const { id } = this.data
    this.getMedal()
    if(id){
      const res = await request.get(api.homeDetail, { userId: id }, { loading: false })
      const info = res?.data
        info.carbonEmissionNum = info.carbonEmissionNum>=1000 ?fixed(info.carbonEmissionNum/1000,3)+'kg': (info.carbonEmissionNum || 0) +'g'
      console.log('用户信息：', info)
      this.setData({
        info
      })

      var communityName = res?.data?.verifyCommunityName
      if (res.data?.complete === 1) {
        if (!communityName) communityName = '居住地认证'
      }
      if(communityName && communityName!=null){
        this.setData({
          detailInfo: communityName?.replace(/单元(.*)层/, '单元'),
          infoComplete: res.data.complete
        })
      }else{
        this.setData({
          detailInfo: null,
          infoComplete: false
        })
      }
    }
  },
  // 获取用户勋章列表数据
  async getMedal() {
    console.log('getget');
    const { id } = this.data
    const res = await request.get(api.medalWall, { userId: id }, { loading: false })
    this.setData({
      medalCount: res?.data?.length || 0,
      medalList: res?.data?.slice(0, 4)
    })
  },
  // 标签页选中变化
  tabChange(e) {
    const tabIndex = e?.currentTarget?.dataset?.index
    if (tabIndex === this.data.tabIndex) return
    this.setData({
      tabIndex,
    })
    this.setData({
      page: 1,
      isDone: false,
    })
    this.getList(1)
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  // 类型滑动开始
  typeTouchStart(event) {
    this.setData({
      typeScrollX: event?.touches?.[0]?.pageX || 0
    })
  },
  // 类型滑动移动
  typeTouchMove(event) {
    const { typeScrollX } = this.data
    const currentX = event?.touches?.[0]?.pageX || 0

    if (typeScrollX - currentX > 50) {
      console.log('右滑')
      this.touchType = 'right'
    } 
    if (currentX - typeScrollX > 50) {
      console.log('左滑')
      this.touchType = 'left'
    }
  },
  // 类型滑动结束
  typeTouchEnd() {
    if (!this.touchType) return
    const { tabIndex } = this.data
    const typeList = ['1', '2']
    const lastIndex = typeList.length - 1
    let currentIndex = typeList.indexOf(tabIndex)

    if (this.touchType === 'left') {
      currentIndex--
      currentIndex = currentIndex < 0 ? 0 : currentIndex
    }
    if (this.touchType === 'right') {
      currentIndex++
      currentIndex = currentIndex > lastIndex ? lastIndex : currentIndex
    }

    if (typeList[currentIndex] !== tabIndex && !this.refresh) {
      this.setData({
        tabIndex: typeList[currentIndex]
      })
      this.getList(1)
      wx.pageScrollTo({
        scrollTop: 0
      })
    }
    this.touchType = null
  },
  // 关注&取关用户
  async followUser(e) {
    const { id, info } = this.data
    if (info.isFollow && e !== false) {
      this.followModal.show()
    } else {
      const res = await request.post(
        (info.isFollow ? api.cancleFollow : api.follow) + id,
        null,
        { loading: false }
      )
      if (res?.httpStatus === 200) {
        wx.showToast({
          icon: 'none',
          title: info.isFollow ? '取消成功' : '关注成功',
        })
        this.followModal.hide()
        this.getInfo()
      }
    }
  },
  // 发提醒
  async warn() {
    if (this.loading) return
    this.loading = true
    const userId = this.data.id
    const res = await request.get(api.sendRemind, { userId }, { loading:false })
    if (res?.httpStatus === 200) {
      wx.showToast({
        icon: 'none',
        title: '已提醒',
        duration: 2000
      })
      this.getInfo()
    }
    this.loading = false
  },
  // 跳转到好友提醒页面
  jumpWarn() {
    jump('circleFriendAlert')
  },
  // 跳转到关注页面
  jumpFollow() {
    const { info } = this.data
    if (info.follow) {
      wx.navigateTo({
        url: `/pages/followList/followList?userId=${info.id}`,
      })
    }
  },
  // 跳转到粉丝页面
  jumpFans() {
    const { info } = this.data
    if (info.vermicelli) {
      wx.navigateTo({
        url: `/pages/followList/followList?userId=${info.id}&isFans=true`,
      })
    }
  },
  // 跳转到勋章墙页面
  jumpMedalWall() {
    const { info } = this.data
    wx.navigateTo({
      url: `/pages/medalWall/medalWall?userId=${info.id}`,
    })
  },
  // 跳转到圈子主页
  async jumpCircle(e) {
    if (this.loading) return
    this.loading = true
    const id = e?.currentTarget?.dataset?.id
    const res = await request.get(api.circleDetail, { id }, { loading: false })
    if (!res?.data?.allow) {
      wx.showToast({
        icon: 'none',
        title: '抱歉，您没有访问权限',
        duration: 2000
      })
    } else {
      jump('circle', { id })
    }
    this.loading = false
  },
  // 跳转至环保成绩单页面
  jumpDetail(){
    let { id, userId } = this.data
    if (id == userId) {
      jump('environmentalPerformance',{ id })
    }
  },
  // 取关确认
  followConfirm() {
    this.followUser(false)
  },
  // 用户点击右上角分享
	onShareAppMessage(e) {
    this.isShareing = true
		return shareOptions('post', e)
  },
  // 页面滚动事件
  onPageScroll(e) {
    this.setData({
      scrollTop: e?.scrollTop,
    });
},
})